import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.provider.Settings
import android.security.KeyPairGeneratorSpec
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.math.BigInteger
import java.nio.charset.StandardCharsets
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.MessageDigest
import java.util.*
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import javax.security.auth.x500.X500Principal

class DeviceUUIDManager private constructor(context: Context) {
    private val context: Context
    private val sharedPreferences: SharedPreferences
    private val keyStore: KeyStore
    private val KEY_ALIAS = "device_uuid_key"
    private val PREFERENCE_NAME = "device_uuid_prefs"
    private val UUID_KEY = "com.example.app.deviceUUID"
    private val IV_KEY = "uuid_iv"
    private val TRANSFORMATION = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        "AES/GCM/NoPadding"
    } else {
        "RSA/ECB/PKCS1Padding"
    }

    init {
        this.context = context.applicationContext
        this.sharedPreferences = this.context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
        this.keyStore = KeyStore.getInstance("AndroidKeyStore")
        this.keyStore.load(null)
        ensureKeyExists()
    }

    companion object {
        @Volatile
        private var instance: DeviceUUIDManager? = null

        fun getInstance(context: Context): DeviceUUIDManager {
            return instance ?: synchronized(this) {
                instance ?: DeviceUUIDManager(context).also { instance = it }
            }
        }
    }

    /**
     * 确保加密密钥存在，兼容API 21+
     */
    private fun ensureKeyExists() {
        try {
            if (!keyStore.containsAlias(KEY_ALIAS)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // API 23及以上使用AES密钥
                    val keyGenerator = KeyGenerator.getInstance(
                        KeyProperties.KEY_ALGORITHM_AES,
                        "AndroidKeyStore"
                    )

                    val keyGenParameterSpec = KeyGenParameterSpec.Builder(
                        KEY_ALIAS,
                        KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
                    )
                        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                        .setKeySize(256)
                        .build()

                    keyGenerator.init(keyGenParameterSpec)
                    keyGenerator.generateKey()
                } else {
                    // API 21-22使用RSA密钥对
                    val start = Calendar.getInstance()
                    val end = Calendar.getInstance()
                    end.add(Calendar.YEAR, 30) // 密钥有效期30年

                    val spec = KeyPairGeneratorSpec.Builder(context)
                        .setAlias(KEY_ALIAS)
                        .setSubject(X500Principal("CN=$KEY_ALIAS"))
                        .setSerialNumber(BigInteger.ONE)
                        .setStartDate(start.time)
                        .setEndDate(end.time)
                        .build()

                    val generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore")
                    generator.initialize(spec)
                    generator.generateKeyPair()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取设备可用的标识信息（完全不依赖特殊权限）
     */
    private fun getDeviceIdentifiers(): String {
        // 1. 使用Android ID（无需权限，最稳定的标识符之一）
        val androidId = Settings.Secure.getString(
            context.contentResolver,
            Settings.Secure.ANDROID_ID
        ) ?: "unknown_android_id"

        // 2. 设备制造商和型号
        val manufacturer = Build.MANUFACTURER ?: "unknown_manufacturer"
        val model = Build.MODEL ?: "unknown_model"

        // 3. 设备品牌和产品名称
        val brand = Build.BRAND ?: "unknown_brand"
        val product = Build.PRODUCT ?: "unknown_product"

        // 4. 设备硬件信息
        val hardware = Build.HARDWARE ?: "unknown_hardware"
        val device = Build.DEVICE ?: "unknown_device"

        // 组合所有信息（不包含需要特殊权限的序列号）
        return "$androidId|$manufacturer|$model|$brand|$product|$hardware|$device"
    }

    /**
     * 基于设备信息生成UUID
     */
    private fun generateUUIDFromDeviceInfo(): String {
        return try {
            val deviceInfo = getDeviceIdentifiers()
            // 使用SHA-256哈希设备信息，然后转换为UUID格式
            val messageDigest = MessageDigest.getInstance("SHA-256")
            val hashBytes = messageDigest.digest(deviceInfo.toByteArray(StandardCharsets.UTF_8))

            // 取前16字节生成UUID
            val uuidBytes = hashBytes.copyOfRange(0, 16)
            UUID.nameUUIDFromBytes(uuidBytes).toString()
        } catch (e: Exception) {
            e.printStackTrace()
            // 如果哈希失败， fallback 到随机UUID
            generateRandomUUID()
        }
    }

    /**
     * 生成随机UUID
     */
    private fun generateRandomUUID(): String {
        return UUID.randomUUID().toString()
    }

    /**
     * 保存UUID到安全存储
     */
    private fun saveUUID(uuid: String): Boolean {
        return try {
            val encryptedData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // API 23+ 使用AES加密
                val secretKey = keyStore.getKey(KEY_ALIAS, null) as SecretKey
                val cipher = Cipher.getInstance(TRANSFORMATION)
                cipher.init(Cipher.ENCRYPT_MODE, secretKey)

                // 保存IV
                val iv = cipher.iv
                sharedPreferences.edit()
                    .putString(IV_KEY, Base64.encodeToString(iv, Base64.NO_WRAP))
                    .apply()

                cipher.doFinal(uuid.toByteArray(StandardCharsets.UTF_8))
            } else {
                // API 21-22 使用RSA加密
                val publicKey = keyStore.getCertificate(KEY_ALIAS).publicKey
                val cipher = Cipher.getInstance(TRANSFORMATION)
                cipher.init(Cipher.ENCRYPT_MODE, publicKey)

                // RSA加密需要处理分段
                encryptRsa(cipher, uuid.toByteArray(StandardCharsets.UTF_8))
            }

            sharedPreferences.edit()
                .putString(UUID_KEY, Base64.encodeToString(encryptedData, Base64.NO_WRAP))
                .apply()

            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 从安全存储获取UUID
     */
    private fun getUUID(): String? {
        return try {
            // 检查是否有保存的数据
            val encryptedDataStr = sharedPreferences.getString(UUID_KEY, null)
            if (encryptedDataStr.isNullOrEmpty()) {
                return null
            }

            val encryptedData = Base64.decode(encryptedDataStr, Base64.NO_WRAP)
            val decryptedData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // API 23+ 使用AES解密
                val ivStr = sharedPreferences.getString(IV_KEY, null)
                if (ivStr.isNullOrEmpty()) {
                    return null
                }

                val iv = Base64.decode(ivStr, Base64.NO_WRAP)
                val secretKey = keyStore.getKey(KEY_ALIAS, null) as SecretKey
                val cipher = Cipher.getInstance(TRANSFORMATION)
                val gcmParameterSpec = GCMParameterSpec(128, iv)

                cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec)
                cipher.doFinal(encryptedData)
            } else {
                // API 21-22 使用RSA解密
                val privateKey = keyStore.getKey(KEY_ALIAS, null)
                val cipher = Cipher.getInstance(TRANSFORMATION)
                cipher.init(Cipher.DECRYPT_MODE, privateKey)

                // RSA解密需要处理分段
                decryptRsa(cipher, encryptedData)
            }

            String(decryptedData, StandardCharsets.UTF_8)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * RSA分段加密（处理长数据）
     */
    private fun encryptRsa(cipher: Cipher, data: ByteArray): ByteArray {
        val outputStream = ByteArrayOutputStream()
        val blockSize = 117 // RSA/ECB/PKCS1Padding 2048位密钥的加密块大小

        var offset = 0
        while (offset < data.size) {
            val length = if (data.size - offset > blockSize) blockSize else data.size - offset
            outputStream.write(cipher.doFinal(data, offset, length))
            offset += length
        }

        return outputStream.toByteArray()
    }

    /**
     * RSA分段解密
     */
    private fun decryptRsa(cipher: Cipher, data: ByteArray): ByteArray {
        val outputStream = ByteArrayOutputStream()
        val blockSize = 128 // RSA/ECB/PKCS1Padding 2048位密钥的解密块大小

        var offset = 0
        while (offset < data.size) {
            val length = if (data.size - offset > blockSize) blockSize else data.size - offset
            outputStream.write(cipher.doFinal(data, offset, length))
            offset += length
        }

        return outputStream.toByteArray()
    }

    /**
     * 获取设备唯一标识符
     * 基于设备公开信息生成，无需任何特殊权限
     */
    fun getDeviceUUID(): String {
        // 尝试从存储中获取已生成的UUID
        val existingUUID = getUUID()
        if (existingUUID != null) {
            return existingUUID
        }

        // 基于设备信息生成UUID
        val newUUID = generateUUIDFromDeviceInfo()

        // 保存生成的UUID
        saveUUID(newUUID)
        return newUUID
    }
}
